<template>
  <div class="risk-assessment">
    <h1>风险等级评估与药物推荐</h1>
    
    <div class="assessment-info">
      <p>基于药物相互作用检测结果和患者特征信息，系统已自动完成风险等级评估，并提供个性化药物推荐。</p>
    </div>
    
    <div class="interactions-list">
      <h2>AI深度分析</h2>
      
      <div v-if="interactions.length > 0">
        <div 
          v-for="interaction in interactions" 
          :key="interaction.id"
          class="interaction-card"
          :class="`risk-${interaction.severity.toLowerCase()}`"
        >
          <div class="interaction-header">
            <h3>药物相互作用</h3>
            <span class="risk-badge" :class="`risk-${interaction.severity.toLowerCase()}`">
              {{ getSeverityText(interaction.severity.toLowerCase()) }}
            </span>
          </div>
          
          <div class="interaction-details">
            <p><strong>涉及药物:</strong> {{ interaction.drugs.join(' + ') }}</p>
            <p><strong>风险描述:</strong> {{ interaction.description }}</p>
            <p><strong>处理建议:</strong> {{ interaction.recommendation }}</p>
            
            <!-- AI深度分析按钮 -->
            <div v-if="!interaction.aiAnalysis && (interaction.severity.toLowerCase() === 'high' || interaction.severity.toLowerCase() === 'medium') && !interaction.aiAnalysisLoading" class="ai-analysis-section">
              <button 
                @click="performAIAnalysis(interaction)"
                class="ai-analysis-btn"
                :disabled="interaction.aiAnalysisLoading"
              >
                执行AI深度分析
              </button>
              <p class="analysis-description">获取个性化风险评估和药物推荐</p>
            </div>
            
            <!-- AI深度分析加载状态 -->
            <div v-else-if="interaction.aiAnalysisLoading" class="ai-analysis-loading">
              <p>AI分析中...</p>
            </div>
            
            <!-- 未分析提示 -->
            <div v-else-if="(interaction.severity.toLowerCase() === 'high' || interaction.severity.toLowerCase() === 'medium') && !interaction.aiAnalysis" class="not-analyzed">
              <p>暂未进行分析</p>
            </div>
            
            <!-- AI深度分析结果 -->
            <div v-else-if="interaction.aiAnalysis" class="ai-analysis-result">
              <div v-if="interaction.aiAnalysis.includes('### 药物相互作用分析报告')">
                <!-- 提取并显示药物相互作用 -->
                <div v-if="extractSection(interaction.aiAnalysis, '相互作用机制')">
                  <h4>药物相互作用机制</h4>
                  <div v-html="formatExtractedSection(extractSection(interaction.aiAnalysis, '相互作用机制') || '')"></div>
                </div>
                
                <!-- 提取并显示处理措施 -->
                <div v-if="extractSection(interaction.aiAnalysis, '处理措施')">
                  <h4>临床处理措施</h4>
                  <div v-html="formatExtractedSection(extractSection(interaction.aiAnalysis, '处理措施') || '')"></div>
                </div>
                
                <!-- 提取并显示药物替换建议 -->
                <div v-if="extractSection(interaction.aiAnalysis, '药物替换')">
                  <h4>药物替换建议</h4>
                  <div v-html="formatExtractedSection(extractSection(interaction.aiAnalysis, '药物替换') || '')"></div>
                </div>
              </div>
              <div v-else>
                <h4>AI深度分析结果</h4>
                <div class="ai-analysis-content" v-html="formatAiAnalysis(interaction.aiAnalysis)"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else class="no-interactions">
        <p>未检测到药物信息</p>
      </div>
    </div>
    
    <div class="navigation-buttons">
      <button @click="goToPatientInfo" class="back-btn">返回患者信息</button>
      <button @click="goToDoctorReview" class="next-btn">医生审核界面</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
// @ts-ignore
import { useStore } from 'vuex'
import { analyzeDrugInteractionWithSparkHttp } from '@/services/index'
import { tencentTranslateService } from '@/services/index'

interface Interaction {
  id: number
  drugs: string[]
  severity: string
  description: string
  recommendation: string
  aiAnalysis?: string
  aiAnalysisLoading?: boolean
}

const store = useStore()
const router = useRouter()

// 获取相互作用数据
const interactions = computed(() => {
  // 创建响应式副本以便我们可以添加加载状态
  return reactive(store.state.interactions.map((interaction: any) => ({
    ...interaction,
    aiAnalysisLoading: false
  })))
})


// 获取患者信息
const patientInfo = computed(() => store.state.patientInfo)

// 获取风险等级文本
const getSeverityText = (severity: string) => {
  switch (severity) {
    case 'high': return '高风险'
    case 'medium': return '中风险'
    case 'low': return '低风险'
    default: return '未知风险'
  }
}

// 性别映射
const genderMap: Record<string, string> = {
  male: '男',
  female: '女',
  other: '其他'
}

// 肝功能映射
const liverFunctionMap: Record<string, string> = {
  normal: '正常',
  mild: '轻度异常',
  moderate: '中度异常',
  severe: '重度异常'
}

// 肾功能映射
const kidneyFunctionMap: Record<string, string> = {
  normal: '正常',
  mild: '轻度异常',
  moderate: '中度异常',
  severe: '重度异常'
}

// 格式化AI分析结果
const formatAiAnalysis = (content: string) => {
  if (!content) return ''
  
  // 将换行符转换为<br>标签
  return content.replace(/\n/g, '<br>')
}

// 提取AI分析的特定部分
const extractSection = (content: string, sectionTitle: string) => {
  if (!content) return null
  
  // 创建正则表达式匹配章节标题
  const sectionRegex = new RegExp(`####\\s*${sectionTitle}[\\s\\S]*?(?=####|$)`, 'g')
  const match = sectionRegex.exec(content)
  
  if (match) {
    // 移除标题行并返回内容
    return match[0].replace(`#### ${sectionTitle}`, '').trim()
  }
  
  return null
}

// 格式化提取的内容
const formatExtractedSection = (content: string) => {
  if (!content) return ''
  
  // 移除多余的换行和格式化内容
  let formatted = content
    .replace(/\n\n/g, '</p><p>')  // 将双换行转换为段落
    .replace(/\n/g, '<br>')       // 将单换行转换为换行标签
    .replace(/^- /gm, '• ')       // 将列表符号转换为HTML符号
  
  // 如果内容不以p标签开头，则添加
  if (!formatted.startsWith('<p>')) {
    formatted = '<p>' + formatted + '</p>'
  }
  
  return formatted
}

// 执行AI分析
const performAIAnalysis = async (interaction: any) => {
  // 设置加载状态
  interaction.aiAnalysisLoading = true
  
  try {
    // 构建患者特征信息
    const patientFeatures = `
      年龄: ${patientInfo.value.age}岁,
      体重: ${patientInfo.value.weight}kg,
      性别: ${genderMap[patientInfo.value.gender] || patientInfo.value.gender},
      肝功能: ${liverFunctionMap[patientInfo.value.liverFunction] || patientInfo.value.liverFunction},
      肾功能: ${kidneyFunctionMap[patientInfo.value.kidneyFunction] || patientInfo.value.kidneyFunction},
      药物过敏史: ${patientInfo.value.allergies.length > 0 ? patientInfo.value.allergies.join(', ') : '无'}
    `.replace(/\s+/g, ' ').trim()
    
    // 构建分析提示
    const prompt = `
      基于以下药物相互作用信息和患者特征，请提供详细的分析报告：
      
      涉及药物: ${interaction.drugs.join(' + ')}
      风险描述: ${interaction.description}
      风险等级: ${getSeverityText(interaction.severity.toLowerCase())}
      处理建议: ${interaction.recommendation}
      
      患者特征: ${patientFeatures}
      
      请按照以下格式提供分析报告：
      ### 药物相互作用分析报告
      #### 相互作用机制
      [详细描述药物之间的相互作用机制]
      #### 处理措施
      [具体的临床处理措施建议]
      #### 药物替换
      [可能的药物替换选项及理由]
    `.replace(/^\s+/gm, '').trim()
    
    // 调用AI服务进行分析
    const aiAnalysis = await analyzeDrugInteractionWithSparkHttp(
      interaction.drugs[0],
      interaction.drugs[1],
      prompt,
      {
        model: 'pro'
      }
    )
    
    // 更新交互对象的AI分析结果
    interaction.aiAnalysis = aiAnalysis
    
    // 将AI分析结果同步更新到Vuex store
    const updatedInteractions = interactions.value.map((item: any) => {
      if (item.id === interaction.id) {
        return { ...item, aiAnalysis }
      }
      return item
    })
    store.commit('SET_INTERACTIONS', updatedInteractions)
  } catch (error) {
    console.error('AI分析出错:', error)
    interaction.aiAnalysis = 'AI分析失败: ' + (error instanceof Error ? error.message : '未知错误')
  } finally {
    // 取消加载状态
    interaction.aiAnalysisLoading = false
  }
}


// 跳转到患者信息页面
const goToPatientInfo = () => {
  router.push('/patient-info')
}

// 跳转到医生审核界面
const goToDoctorReview = () => {
  router.push('/doctor-review')
}
</script>
<style scoped>
.risk-assessment {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.risk-assessment h1 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 10px;
  font-size: 2rem;
}

.assessment-info {
  background-color: #e3f2fd;
  border: 1px solid #bbdefb;
  border-radius: 10px;
  padding: 25px;
  margin-bottom: 30px;
  text-align: center;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.assessment-info p {
  color: #2c3e50;
  font-size: 1.1rem;
  margin: 0;
}

.interactions-list h2 {
  color: #2c3e50;
  text-align: center;
  font-size: 1.8rem;
  margin: 30px 0 20px;
}

.interaction-card {
  background: white;
  border-radius: 10px;
  padding: 25px;
  margin-bottom: 25px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  border-left: 5px solid #ddd;
}

.interaction-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0,0,0,0.12);
}

.interaction-card.risk-high {
  border-left-color: #e74c3c;
}

.interaction-card.risk-medium {
  border-left-color: #f39c12;
}

.interaction-card.risk-low {
  border-left-color: #27ae60;
}

.interaction-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.interaction-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.4rem;
}

.risk-badge {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 1rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.risk-badge.risk-high {
  background-color: #ffcdd2;
  color: #c62828;
}

.risk-badge.risk-medium {
  background-color: #fff9c4;
  color: #f9a825;
}

.risk-badge.risk-low {
  background-color: #c8e6c9;
  color: #2e7d32;
}

.interaction-details p {
  margin: 12px 0;
  color: #555;
  font-size: 1rem;
  line-height: 1.5;
}

.interaction-details strong {
  color: #2c3e50;
}

.ai-analysis-section {
  text-align: center;
  margin: 25px 0;
  padding: 25px;
  background-color: #f1f8ff;
  border-radius: 8px;
  border: 1px dashed #3498db;
}

.ai-analysis-btn {
  background-color: #3498db;
  color: white;
  border: none;
  padding: 14px 28px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1.1rem;
  font-weight: 600;
  margin: 15px 0;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.ai-analysis-btn:hover:not(:disabled) {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0,0,0,0.15);
}

.ai-analysis-btn:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.analysis-description {
  color: #7f8c8d;
  font-size: 1rem;
  margin: 10px 0 0;
}

.ai-pending {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff3e0;
  border-radius: 8px;
  color: #f57c00;
  text-align: center;
  font-weight: 500;
}

.ai-analysis-loading {
  margin-top: 20px;
  padding: 25px;
  background-color: #e3f2fd;
  border-radius: 8px;
  color: #1976d2;
  text-align: center;
  font-size: 1.1rem;
  font-weight: 500;
}

.not-analyzed {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff3e0;
  border-radius: 8px;
  color: #f57c00;
  text-align: center;
  font-weight: 500;
}

.ai-analysis-result {
  margin-top: 25px;
  padding: 25px;
  background-color: #e8f5e9;
  border-radius: 8px;
  border-left: 4px solid #27ae60;
}

.ai-analysis-result h4 {
  margin-top: 0;
  color: #2c3e50;
  font-size: 1.3rem;
  border-bottom: 1px solid #c8e6c9;
  padding-bottom: 10px;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 40px;
  padding: 25px 0;
}

.back-btn,
.next-btn {
  padding: 14px 28px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 1.1rem;
  font-weight: 600;
  transition: all 0.3s;
  box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}

.back-btn {
  background-color: #95a5a6;
  color: white;
}

.back-btn:hover {
  background-color: #7f8c8d;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0,0,0,0.15);
}

.next-btn {
  background-color: #3498db;
  color: white;
}

.next-btn:hover {
  background-color: #2980b9;
  transform: translateY(-2px);
  box-shadow: 0 6px 8px rgba(0,0,0,0.15);
}

@media (max-width: 768px) {
  .risk-assessment {
    padding: 20px;
  }
  
  .interaction-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .navigation-buttons {
    flex-direction: column;
    gap: 15px;
  }
  
  .back-btn,
  .next-btn {
    width: 100%;
    padding: 12px;
  }
}
</style>